package com.sltx.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 *
 */
@Component
public class ImageUtil {


    //文件保存路径
    @Value("${file-save-path}")
    private String fileSavePath;

    //项目启动根目录
    @Value("${server.servlet.context-path}")
    private String locationPath;

    // 上传图片格式
    public String getImageUrl(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
        //后半段目录：
        String directory = "image/";

        if (file.isEmpty()){
            return "请选择文件上传";
        }

        File dir = new File(fileSavePath + directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 获取文件名+后缀
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        System.out.println(suffix);
        if (!".png".equals(suffix) && !".jpg".equals(suffix) && !".jpeg".equals(suffix) && !".bmp".equals(suffix) && !".pdf".equals(suffix)){

            return "文件格式不对";
        }

        //给文件重新设置一个名字
        String newFileName= UUID.randomUUID().toString().replaceAll("-", "")+ suffix;
        //创建这个新文件
        File newFile = new File(fileSavePath + directory + newFileName);
        //复制操作
        try {
            file.transferTo(newFile);

            //linux下图片路径
            String url = fileSavePath + directory + newFileName;
            System.out.println("图片上传，访问URL：" + url);
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败";
        }
    }



    // 上传文件格式
    public Map<String,String>  getFileUrl(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {

        Map<String,String> result = new HashMap<String,String>();

        //后半段目录：
        String directory = "znbg/";

        if (file.isEmpty()){
            result.put("msg","请选择文件上传");
            return result;
        }

        File dir = new File(fileSavePath + directory );
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 获取文件名+后缀
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);

        if (fileName.lastIndexOf(".") != -1) {
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            System.out.println(suffix);
            if (!".doc".equals(suffix) && !".docx".equals(suffix) && !".xls".equals(suffix) && !".xlsx".equals(suffix) && !".pdf".equals(suffix)){
                result.put("msg","文件格式不对");
                return result;
            }

            //给文件重新设置一个名字
            String newFileName= UUID.randomUUID().toString() + suffix;
            //创建这个新文件
            File newFile = new File(fileSavePath + directory + newFileName);

            try {
                //复制操作
                file.transferTo(newFile);

                String inPath = newFile.toString();

                String[] split = inPath.split("znbg");
                // 获取文件名称和后缀
                StringBuilder sb = new StringBuilder(split[split.length-1]);
                sb.deleteCharAt(0);
                //获取字符串后缀
                String s = sb.substring(sb.lastIndexOf("."));
                // 获取字符串前缀
                String p = sb.substring(0,sb.lastIndexOf("."));

                if (".doc".equals(s) || ".docx".equals(s)){

                    String outPath = split[0] + directory + p + ".pdf";

                    System.out.println("out   "+outPath);
                    fileToPDF.doc2pdf(inPath, outPath);
                    String pdf = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + locationPath + fileSavePath + directory + p + ".pdf";
                    result.put("pdf",pdf);

                }else if (".xls".equals(s) || ".xlsx".equals(s)){
                    String outPath = split[0] + directory + p + ".pdf";
                    System.out.println("out   "+outPath);
                    fileToPDF.excel2pdf(inPath, outPath);

                    String pdf = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + locationPath + fileSavePath + directory + p + ".pdf";
                    result.put("pdf",pdf);
                }else if (".pdf".equals(s)){
                    String pdf =  request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + locationPath + fileSavePath + directory + newFileName;
                    result.put("pdf",pdf);
                }

                //生成url路径
                /*
                getScheme() 获取http
                getServerName() 获取IP
                getServerPort() 获取端口
                */
                String url =  request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + locationPath + fileSavePath + directory + newFileName;
                System.out.println("图片上传，访问URL：" + url);
                result.put("url",url);
            } catch (IOException e) {
                e.printStackTrace();
                result.put("msg","上传失败");
            }
        }

        return result;
    }
}
